//
//  PictureSelectViewController.swift
//  SinaWeibo
//
//  Created by Tony-ztb on 15/12/28.
//  Copyright © 2015年 Tony-ztb. All rights reserved.
//

import UIKit
import SnapKit

private let reuseIdentifier = "Cell"
private let rowCount: CGFloat = 3
private let margin: CGFloat = 5
private let maxImageCount = 9

class PictureSelectViewController: UICollectionViewController {
    
    // 选择添加的图片数组
    var imageList = [UIImage]()
    
    init() {
        // 设置每个cell的宽度
        let itemW = (screenW - (rowCount + 1) * margin) / rowCount
        // 流水布局
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSizeMake(itemW, itemW)
        layout.minimumLineSpacing = margin
        layout.minimumInteritemSpacing = margin
        // 设置组间距
        layout.sectionInset = UIEdgeInsets(top: margin, left: margin, bottom: margin, right: margin)
        
        super.init(collectionViewLayout: layout)
        
        collectionView?.backgroundColor = UIColor.whiteColor()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    

    override func viewDidLoad() {
        super.viewDidLoad()

        // Register cell classes
        self.collectionView!.registerClass(PictureSelectCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        
        

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    
    // MARK: UICollectionViewDataSource
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        let delta = imageList.count == maxImageCount ? 0 : 1
        return imageList.count + delta
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! PictureSelectCell
        
        
        cell.delegate = self
        
        if indexPath.item == imageList.count {
            cell.image = nil
        } else {
            cell.image = imageList[indexPath.item]
        }

        if indexPath.item == 0 {
            choosePicture(cell)
        }
        
        
        return cell
    }

}

// 实现协议方法
extension PictureSelectViewController: PictureSelectCellDelegate {
    
    func deletePicture(cell: PictureSelectCell) {
        print(__FUNCTION__)
        
        if let index = collectionView?.indexPathForCell(cell) {
            // 移除要删除图片的下标
            imageList.removeAtIndex(index.item)
            // 刷新
            collectionView?.reloadData()
        }
        
    }
    
    func choosePicture(cell: PictureSelectCell) {
        print(__FUNCTION__)
        // 如果cell有图片 则直接返回
        if cell.image != nil {
            return
        }
        
        // 图片选择器控件
        let picker = UIImagePickerController()
        
        presentViewController(picker, animated: true, completion: nil)
        
        picker.delegate = self
        
    }
}

// 图片选择器代理
extension PictureSelectViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        // 选择的图片添加到数组中
        imageList.append(image)
        // 刷新
        collectionView?.reloadData()
        // 跳转回上一个界面
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    
}


// 协议方法
@objc protocol PictureSelectCellDelegate: NSObjectProtocol {
    // 定义协议方法
    optional func deletePicture(cell: PictureSelectCell)
    optional func choosePicture(cell: PictureSelectCell)
}



class PictureSelectCell: UICollectionViewCell {
    // MARK: - 定义外部属性
    var image: UIImage? {
        didSet {
            deleteBtn.hidden = image == nil
            addBtn.setImage(image, forState: .Normal)
            
        }
    }
    
    
    @objc private func addBtnDidClick() {
        delegate?.choosePicture?(self)
    }
    
    @objc private func deleteBtnDidClick() {
        delegate?.deletePicture?(self)
    }
    
    
    
    // 声明弱引用的代理对象
    weak var delegate: PictureSelectCellDelegate?
    
    // MARK: - 重写构造方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 设置页面 和 布局
    private func setupUI() {
        
        addBtn.imageView?.contentMode = .ScaleAspectFill
        contentView.addSubview(addBtn)
        contentView.addSubview(deleteBtn)
        
        // 设置约束
        addBtn.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
        
        deleteBtn.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(addBtn.snp_top)
            make.right.equalTo(addBtn.snp_right)
        }
        
        
        addBtn.addTarget(self, action: "addBtnDidClick", forControlEvents: .TouchUpInside)
        deleteBtn.addTarget(self, action: "deleteBtnDidClick", forControlEvents: .TouchUpInside)
        
    }
    
    // MARK: - 懒加载所有的子视图
    private lazy var deleteBtn: UIButton = UIButton(imageName: nil, backImageName: "compose_photo_close")
    private lazy var addBtn: UIButton = UIButton(imageName: nil, backImageName: "compose_pic_add")
}

